package com.service.weChatWifiLogin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.service.config.utils.JsonXMLUtils;
import com.service.config.utils.ModelMapperUtil;
import com.service.weChatWifiLogin.dto.WeiChatDto;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

import java.util.HashMap;

import static com.service.config.constant.ApiUrlConstants.*;

/**
 * @author
 * @version 1.0
 * @date 2021/6/24 8:49
 */
@Service
public class QueryWeiChatServiceImpl {
    @Resource
    RestTemplate restTemplate;
    /**
     * 拼接微信交互的url
     * @param code
     * @param url
     * @param customerAppId
     * @param customerSecret
     * @return
     */
    public String getUrl(String code, String url, String customerAppId, String customerSecret) {
        url = url.concat(WEI_XIN_CODE2_SESSION+ customerAppId +secret+ customerSecret +js_code+code);
        return url;
    }

    /**
     * 与微信服务端交互
     * @param url
     * @return
     */
    public HashMap getOpenId (String url) throws Exception {
        HashMap map = new HashMap();
        HttpEntity<String> requestEntity = new HttpEntity<>("");
        ResponseEntity<JSONObject> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, JSONObject.class);
        WeiChatDto weiChatDto = ModelMapperUtil.strictMap(response.getBody(), WeiChatDto.class);
        if (weiChatDto.getErrcode()==null || weiChatDto.getErrcode().equals("0")) {
            map.put("weiChatDto", JsonXMLUtils.obj2json(weiChatDto));
        }else {
            map.put("errcode",JsonXMLUtils.obj2json(weiChatDto));
        }
        return map;
    }
}
